//import store from '@/store';
//import config from '../../common/config/config';
import globalConfig from '@/common/config/config';
import { getToken } from '@/utils/auth';
import { errcode } from '../../common/constant/constants';
import modal from '@/plugins/modal';
//import { toast, showConfirm, tansParams } from '@/utils/common'
import type { RequestConfig, ResponseData } from '@/types/request'

const timeout = 15000;//前端请求等待超时时间
const errCode = errcode;//错误码
const baseUrl = globalConfig.baseUrl;//网络请求的域名或ip
const baseHeader = globalConfig.header;

const request = <T>(config : RequestConfig) : Promise<ResponseData<T>> => {
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	//请求头设置
	config.header = { ...baseHeader, ...(config.header || {}) };
	//请求token的设置
	if (getToken() && !isToken) {
		config.header['Authorization'] = 'Bearer ' + getToken()
		//config.header['clientid'] = clientId
	}
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + modal.tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	return new Promise((resolve, reject) => {
		uni.request({
			method: config.method || 'GET',
			timeout: config.timeout || timeout,
			url: config.baseUrl || baseUrl + config.url,
			data: config.data,
			header: config.header,
			dataType: 'json'
		}).then(response => {
			/* let [error, res] = response
			 if (error) {
			   toast('后端接口连接异常')
			   reject('后端接口连接异常')
			   return
			 } */
			const res = response
			const data : ResponseData<T> = res.data as ResponseData<T>
			const statusCode = res.statusCode
			const code = data.code || 200
			// @ts-ignore
			const msg : string = errCode.code || data.msg || errCode.default
			console.log("返回是：",res);
			if (code === 401) {
				modal.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then((res:any) => {
					if (res.confirm) {
						// store.dispatch('LogOut').then((res: any) => {
						//   uni.reLaunch({ url: '/pages/login' })
						// })
					}
				})
				reject('无效的会话，或者会话已过期，请重新登录。')
			} else if (code === 500) {
				modal.msg(msg);
				reject('500')
			} else if (code !== 200) {
				modal.msg(msg);
				reject(code)
			}else if (statusCode === 500){
				console.log('执行了这里');
				modal.msg('请求异常');
			}
			resolve(data)
		})
			.catch(error => {
				let { message } = error
				if (message === 'Network Error') {
					message = '后端接口连接异常'
				} else if (message.includes('timeout')) {
					message = '系统接口请求超时'
				} else if (message.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				}
				modal.msg(message);
				reject(error)
			})
	})
}

export default request